<?php
/**
* 框架通用常用方法
* @author y@ng
* @copyright 2014
* @version 0.0.1
*/


/**
* 生成url
* @param string $ctrl
* @param string $method
* @return string
*/
function U($ctrl, $method, $param=''){
	if (is_array($param)){
		$strParam = '';
		foreach ($param as $key => $value) {
			if (!empty($value)) {
				$strParam .= $key . YYK::$config['pathinfoSeparator'] . $value . YYK::$config['pathinfoSeparator'];
			}
		}
		$strParam = trim($strParam, YYK::$config['pathinfoSeparator']);
	}
	else
		$strParam = $param;

	// id=1&num=2

	$url = /*rtrim(pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME) , YYK::$config['pathinfoSeparator']).*/ YYK::$config['pathinfoSeparator'] .
			$ctrl . YYK::$config['pathinfoSeparator'] .
			$method ;
	if ($strParam) {
		$url .= YYK::$config['pathinfoSeparator'] . $strParam;
	}

	if (isset(YYK::$config['urlFix'])) {
		$url .= YYK::$config['urlFix'];
	}
	return $url;
}

/**
* 重定向跳转
* @param string $ctrl
* @param string $method
* @return void
*/
function R($ctrl, $method, $param){
	$url = U($ctrl, $method, $param);
	header('Location: ' . $url);
	exit();
}

/**
* 根据标签返回对应语言包的内容
* @param string $mark
* @return string
*/
function L($mark){
	static $lang;
	if (isset($lang) && is_array($lang)){}
	else{
		$lang = include_once(YYK::$APP_path. DIRECTORY_SEPARATOR . 'Lang' . DIRECTORY_SEPARATOR . getLang() . '.php');
	}
	return isset($lang[$mark]) ? $lang[$mark] : $mark ;
}

/**
* 设置默认语言
* @param string $lang
* @return void
*/
function setLang($lang){
	if (file_exists(YYK::$APP_path. DIRECTORY_SEPARATOR . 'Lang' . DIRECTORY_SEPARATOR . $lang . '.php') && YYK::$defaultLang != $lang) {
		setcookie('__defaultLang', $lang, time()+86400*365, '/');
		YYK::$defaultLang = $lang;
	}
}

/**
* 获取默认语言
* @param string $lang
* @return string
*/
function getLang(){
	if (! YYK::$defaultLang) {
		if (isset($_COOKIE['__defaultLang'])) {
			return $_COOKIE['__defaultLang'];
		}
		else{
			$lang = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
			$lang = $lang[0];
			if (!file_exists(YYK::$APP_path. DIRECTORY_SEPARATOR . 'Lang' . DIRECTORY_SEPARATOR . $lang . '.php')) {
				$lang = YYK::$config['defaultLang'];
			}
			setLang($lang);
			return $lang;
		}
	}
	else{
		return YYK::$defaultLang;//$_COOKIE['__defaultLang'];
	}
}


function getIP() { 
	if (isset($_SERVER)) {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
			$realip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { 
			$realip = $_SERVER['HTTP_CLIENT_IP']; 
		} else { 
			$realip = $_SERVER['REMOTE_ADDR']; 
		} 
	}
	else {
		if (getenv("HTTP_X_FORWARDED_FOR")) { 
			$realip = getenv( "HTTP_X_FORWARDED_FOR"); 
		} elseif (getenv("HTTP_CLIENT_IP")) { 
			$realip = getenv("HTTP_CLIENT_IP"); 
		} else { 
			$realip = getenv("REMOTE_ADDR"); 
		} 
	} 
	return $realip; 
}

function getIps() {
	$ip = '';
	if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] . ';';
	}
	if(isset($_SERVER['REMOTE_ADDR'])  && !empty($_SERVER['REMOTE_ADDR'])) {
		$ip .= $_SERVER['REMOTE_ADDR'] . ',';
	}
	if(isset($_SERVER['HTTP_CLIENT_IP'])  && !empty($_SERVER['HTTP_CLIENT_IP'])) {
		$ip .= $_SERVER['HTTP_CLIENT_IP'];
	}
	return $ip;
}

function isEmail($email){
	/*
	if (ereg("/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/i",$email)){
		return true;
	}
	else{
		return false;
	}
	*/
	if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
		return true;
	}
	else
		return false;
}

//错误提示信息
function E($str, $url='', $wait=3){
	if ($url=="") {
		if (empty($_SERVER['HTTP_REFERER']) ) {
			$url = "";
			$wait = 0;
		}else{
			$url = $_SERVER['HTTP_REFERER'] ;
		}
	}
	if (isset(YYK::$config['tplHit']['E']) && file_exists(YYK::$APP_path . DIRECTORY_SEPARATOR . YYK::$config['tplHit']['E'] )) {
		$content = file_get_contents(YYK::$APP_path . DIRECTORY_SEPARATOR . YYK::$config['tplHit']['E']);
	}
	else{
		$content = file_get_contents(YYK::getYYK_path() . '/tpl/E.html');
	}
	$content = str_replace('{$str}', $str, $content);
	$content = str_replace('{$url}', $url, $content);
	$content = str_replace('{$wait}', $wait, $content);
	echo $content;
	exit;
}

//操作成功提示页
function S($str, $url='', $wait=3){
	if ($url=="") {
		$url = $_SERVER['HTTP_REFERER'] ;//"javascript:history.go(-1);";
	}
	if (isset(YYK::$config['tplHit']['S']) && file_exists(YYK::$APP_path . DIRECTORY_SEPARATOR . YYK::$config['tplHit']['S'] )) {
		$content = file_get_contents(YYK::$APP_path . DIRECTORY_SEPARATOR . YYK::$config['tplHit']['S']);
	}
	else{
		$content = file_get_contents(YYK::getYYK_path() . '/tpl/S.html');
	}
	$content = str_replace('{$str}', $str, $content);
	$content = str_replace('{$url}', $url, $content);
	$content = str_replace('{$wait}', $wait, $content);
	echo $content;
	exit;
}

//发送邮件
function sendMail($receiver, $subject, $content){
	$mail = new PHPMailer();

	$mail->IsSMTP();									// telling the class to use SMTP
	$mail->CharSet = "UTF-8";						// 设置字符集编码
	$mail->Encoding = "base64";						//设置文本编码方式
	$mail->SMTPSecure = 'ssl';
	$mail->SMTPAuth      = true;                  // enable SMTP authentication
	$mail->SMTPKeepAlive = true;                  // SMTP connection will not close after each email sent
	$mail->Host          = "smtp.exmail.qq.com"; // sets the SMTP server
	$mail->Port          = 465;                    // set the SMTP port for the GMAIL server
	$mail->Username      = "service@ctssd.com"; // SMTP account username
	$mail->Password      = "Qq123456789";        // SMTP account password
	$mail->SetFrom('service@ctssd.com', '港中旅(山东)通知服务');
	//$mail->AddReplyTo('sunhaobo@qingdaonews.com', 'sunhaobo@qingdaonews.com');//抄送
	$mail->Subject       = $subject;
	$mail->AltBody     = $content;		 // 不支持html格式的邮件服务器应用此文本
	$mail->MsgHTML($content);
	$mail->AddAddress($receiver);

	$mail->Send();

	$mail->ClearAddresses();
	$mail->ClearAttachments();
}


function _404(){
	header('HTTP/1.1 404 Not Found'); 
	header("status: 404 Not Found"); 
	readfile( strlen(YYK::$config['_404']) ? YYK::$config['_404'] : '/alidata/www/onps/404.html');
}

/**
* 获取IP归属地等信息
* @param string $ip
* @return array
*/
function getIpInfo($ip){
	$json = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip);
	$arr = json_decode($json, true);
	if (isset($arr['code']) && $arr['code']==0) {
		return $arr['data'];
	}
	else
		return false;
}


/**
* 判断客户端浏览器是否是微信
* @return boolean
*/
function isWX(){
	if(strpos($_SERVER['HTTP_USER_AGENT'],"MicroMessenger")){
		return true;
	}
	else{
		return false;
	}
}
function isWeChat(){
	return isWX();
}

/**
* 获得当前访问的url
* @return string
*/
function currentUrl(){
	return "http://".$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

/**
* 获取http请求头信息,返回数组
* @return array
*/
function getHttpHeader(){
	foreach ($_SERVER as $name => $value) {
		if (substr($name, 0, 5) == 'HTTP_') {
			$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
		}
	}
	return $headers;
}

/**
* url重定向
* @param string $url
*/
function redirect($url){
	header('Location: ' . $url);
	exit(0);
}

function array_case($val, $case ='lower'){
	switch (strtolower($case)) {
		case 'lower':
			return strtolower($val);
			break;
		case 'upper':
			return strtoupper($val);
			break;
		default:
			return $val;
			break;
	}
}
//文件上传通用方法
/*
upload 上传表单中文件字段名称
ext 允许上传的文件后缀
size 允许的文件大小kb
path 上传文件保存到路径
file 上传文件保存主文件名
*/
function upload($arr){
	if (!isset($arr['upload'])) {
		return array('result'=>false, 'message'=>'上传文件为空');
	}

	if (isset($_FILES[$arr['upload']]["error"]) && !empty($_FILES[$arr['upload']]["error"]) ){
		return array('result'=>false, 'message'=>'文件上传失败' . $_FILES[$arr['upload']]["error"]);
	}

	$ext = strtolower( pathinfo($_FILES[$arr['upload']]["name"], PATHINFO_EXTENSION) );
	if (isset($arr['ext'])) {
		if (is_array($arr['ext'])) {
			$arr_ext = array_map("array_case", $arr['ext']);
			//var_dump($arr_ext );
			if (in_array($ext, $arr_ext)) {
				;
			}
			else{
				return array('result'=>false, 'message'=>'非法文件类型');
			}
		}
		else{
			if ( $ext == strtolower($arr['ext']) ) {
				;
			}
			else{
				return array('result'=>false, 'message'=>'非法文件类型');
			}
		}
	}

	if (isset($arr['size']) && is_numeric($arr['size']) && $arr['size']>0) {
		if($_FILES[$arr['upload']]["size"] > $arr['size'] * 1000){
			return array('result'=>false, 'message'=>'文件太大');
		}
	}

	if (isset($arr['file'])) {
		$file = $arr['file'] . '.' . $ext;
	}
	else{
		$file = md5_file($_FILES[$arr['upload']]["tmp_name"]) . '.' . $ext;
	}

	if(move_uploaded_file($_FILES[$arr['upload']]["tmp_name"], rtrim($arr['path'], '/') . '/' . $file)){
		return array('result'=>true, 'message'=> $file );
	}
	else{
		return array('result'=>false, 'message'=>'文件上传失败' );
	}
}

//将一个多维数组转化为以指定字段值为key的数组
function getResultAsKey($array, $key){
	if(!function_exists("array_column")){
		$result = array();
		foreach ($array as $k => $item) {
			if (empty($key)) {
				$keys = array_keys($item);
				$key = $keys[0];
			}
			if (array_key_exists($key, $item)) {
				$result[$item[$key]] = $item;
			}
		}
	}else{
		$result = array_column($array, NULL, $key);
	}
	return $result;
}
function getFileExt($file){
	return pathinfo($file, PATHINFO_EXTENSION);
}
